import dash
import uuid
import time
from dash import html, dcc
import feffery_antd_components as fac
from dash.dependencies import Input, Output, State

task_progress_records = {}

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        # 注入url监听
        dcc.Location(id='url'),

        # 注入任务id信息
        dcc.Store(id='task-id'),

        # 注入轮询
        dcc.Interval(
            id='interval',
            interval=500
        ),

        fac.AntdSpace(
            [
                html.Div(
                    fac.AntdProgress(
                        id='progress-demo',
                        percent=0
                    ),
                    style={
                        'width': '200px'
                    }
                ),

                fac.AntdSpin(
                    fac.AntdButton(
                        '开始运算',
                        id='start-calculate'
                    ),
                    text='执行任务中...',
                    style={
                        'right': '10px'
                    }
                )
            ],
            direction='vertical'
        )
    ],
    style={
        'padding': '100px'
    }
)


@app.callback(
    Output('task-id', 'data'),
    Input('url', 'pathname')
)
def create_task_id(pathname):
    return {
        'task_id': str(uuid.uuid4())
    }


@app.callback(
    Output('start-calculate', 'disabled'),
    Input('start-calculate', 'nClicks'),
    State('task-id', 'data'),
    prevent_initial_call=True
)
def start_task(nClicks, data):
    if nClicks:
        # 执行任务阶段1
        time.sleep(2)
        task_progress_records[data['task_id']] = '阶段1'

        # 执行任务阶段2
        time.sleep(2)
        task_progress_records[data['task_id']] = '阶段2'

        # 执行任务阶段3
        time.sleep(2)
        task_progress_records[data['task_id']] = '阶段3'

        # 执行任务阶段4
        time.sleep(2)
        task_progress_records[data['task_id']] = '阶段4'

        # 执行任务阶段5
        time.sleep(2)
        task_progress_records[data['task_id']] = '阶段5'

    return dash.no_update


@app.callback(
    Output('progress-demo', 'percent'),
    Input('interval', 'n_intervals'),
    State('task-id', 'data'),
    prevent_initial_call=True
)
def update_progress_percent(n_intervals, data):
    if task_progress_records.get(data['task_id']):
        return 20 * int(task_progress_records[data['task_id']].replace('阶段', ''))

    return dash.no_update


if __name__ == '__main__':
    app.run_server(debug=True)
